
<template>
  <div>
    <van-nav-bar
      fixed
      title="编辑地址"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <van-address-edit
      :area-list="areaList"
      show-postal
      show-delete
      show-set-default
      show-search-result
      :search-result="searchResult"
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @delete="onDelete"
      @change-detail="onChangeDetail"
      :address-info="addressInfo"
    />
  </div>
</template>

<script>
import { Toast } from "vant";
import { areaList } from "@vant/area-data";

export default {
  data() {
    return {
      areaList,
      searchResult: [],
      addressInfo: {},
    };
  },
  mounted() {
    this.$store.commit("SET_HEADER_FOOTER", {
      showSearchHeader: true,
      headerName: "编辑地址",
      pageName: "addressEdit",
      showFooter: false,
    });
    let id = this.$route.query.id;
    if (id) {
      this.getEditAddress(id);
    }
  },
  methods: {
    //保存
    onSave(content) {
      console.info(content);
      let addressList = getStore({ name: "address_list" });
      if (!addressList) {
        addressList = [];
      }
      //默认地址只能一个
      if (content.isDefault) {
        addressList.forEach((item) => {
          if (item.isDefault) {
            item.isDefault = false;
          }
        });
      }
      if (content.id) {
        //编辑
        addressList.forEach((item, index) => {
          if (item.id == content.id) {
            addressList[index] = content;
          }
        });
      } else {
        //新增
        let id = addressList.length + 1;
        content["id"] = id;
        addressList.unshift(content);
      }
      setStore({ name: "address_list", content: addressList });
      this.$toast.success("保存成功");
      this.$router.go(-1);
    },
    onDelete() {
      if (this.addressInfo.id) {
        //删除
        let addressList = getStore({ name: "address_list" });
        if (addressList) {
          addressList.forEach((item, index) => {
            if (item.id == this.addressInfo.id) {
              addressList.splice(index, 1);
              setStore({ name: "address_list", content: addressList });
              this.$toast.success("保存成功");
            }
          });
        }
      }
      this.addressInfo = {};
    },
    //获取编辑的地址
    getEditAddress(id) {
      let addressList = getStore({ name: "address_list" });
      if (addressList) {
        addressList.forEach((item) => {
          if (item.id == id) {
            this.addressInfo = item;
          }
        });
      }
    },
    onChangeDetail(val) {
      if (val) {
        this.searchResult = [
          {
            name: "黄龙万科中心",
            address: "杭州市西湖区",
          },
        ];
      } else {
        this.searchResult = [];
      }
    },
  },
};
</script>